<template>
  <div class="container">
    
    <div class="controls">
      <div class="search-box">
        <i class="fas fa-search"></i>
        <input type="text" v-model="searchQuery" placeholder="搜索订单号或产品代码...">
      </div>

      <div class="order-stats">
        <span class="stat-label">订单总数：</span>
        <span class="stat-value">{{ filteredOrders.length }}</span>
      </div>
      
      <div class="legend">
        <div class="legend-item">
          <div class="legend-color" style="background-color: #ff6b6b;"></div>
          <span>计划数量</span>
        </div>
        <div class="legend-item">
          <div class="legend-color" style="background-color: #51cf66;"></div>
          <span>已派工数量</span>
        </div>
        <div class="legend-item">
          <div class="legend-color" style="background-color: #339af0;"></div>
          <span>已入库数量</span>
        </div>
      </div>
    </div>
    
    <div class="content">
      <div class="order-list fixed-scroll" style="width: 60%">
        <table class="order-table">
          <thead>
            <tr>
              <th style="background-color: #2c3e50; color: white;">订单号</th>
              <th style="background-color: #2c3e50; color: white;">产品代码</th>
              <th style="background-color: #2c3e50; color: white;">毛坯尺寸</th>
              <th style="background-color: #2c3e50; color: white;">首批日期</th>
              <th style="background-color: #2c3e50; color: white;">计划数量</th>
              <th style="background-color: #2c3e50; color: white;">订单总重</th>
              <th style="background-color: #2c3e50; color: white;">订单状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="order in filteredOrders" 
                :key="order.id"
                :class="{selected: selectedOrder && selectedOrder.id === order.id}"
                @click="selectOrder(order)">
              <td>{{ order.orderNumber }}</td>
              <td>{{ order.productCode }}</td>
              <td>{{ order.roughSize }}</td>
              <td>{{ order.firstBatchDate }}</td>
              <td>{{ order.planQuantity }}</td>
              <td>{{ order.totalWeight }}</td>
              <!-- 在tbody中添加状态单元格 -->
              <td>
                <!-- <span>{{ orderStatusText(order) }}</span> -->
                <span v-if="getProcessDelayStatus(order)" class="delay-tag">
                  {{ getProcessDelayStatus(order) }}
                </span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div class="plan-comparison fixed-scroll">
        <div v-if="selectedOrder">
          <div class="stat-box">
            <div class="stat-title">订单概览 - {{ selectedOrder.orderNumber }}</div>
            <div class="stat-content">
              <div class="stat-item">
                <div class="stat-value">{{ selectedOrder.planQuantity }}</div>
                <div class="stat-label">计划数量</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ selectedOrder.productWeight }}</div>
                <div class="stat-label">产品单重</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ selectedOrder.machineType }}</div>
                <div class="stat-label">设备类型</div>
              </div>
            </div>
          </div>
          
          <h3 style="margin: 15px 0 10px; color: #2c3e50;">生产进度对比</h3>
          
          <div v-for="(process, index) in processes" :key="index" class="process-bars">
            <div class="process-title">
              <span>{{ process.name }}</span>
              <span>{{ process.ratio || 0 }}%</span>
            </div>
            <div class="process-bar-container">
              <div class="plan-bar" :style="{width: process.planWidth + '%'}"></div>
              <div class="dispatched-bar" :style="{width: process.dispatchedWidth + '%'}"></div>
              <div class="completed-bar" :style="{width: process.completedWidth + '%'}"></div>
              <div class="process-value">
                {{ process.completed || 0 }} / {{ process.dispatched || 0  }} / {{ process.plan || 0 }}
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="no-selection">
          <div>
            <i class="fas fa-mouse-pointer fa-2x" style="margin-bottom: 15px;"></i>
            <p>请从左侧列表中选择一个订单查看生产进度</p>
          </div>
        </div>
      </div>
    </div>
    
  </div>
</template>

<script>
import { debounce } from 'lodash';
export default {
  name: 'OrderProgressComparison',
  data() {
    return {
      searchQuery: '',
      selectedOrder: null,
      orders: [
        {
          id: 1,
          orderNumber: 'ORD-2023-001',
          productCode: 'PC-1001',
          roughSize: '120×80×40mm',
          firstBatchDate: '2023-06-10',
          planQuantity: 5000,
          productWeight: 1.2,
          totalWeight: 6000,
          machineType: 'CNC-5X',
          processes: {
            smelting: { plan: 5000, dispatched: 4800, completed: 4200 },
            hydrogen: { plan: 5000, dispatched: 4200, completed: 3800 },
            jetMill: { plan: 5000, dispatched: 4000, completed: 3200 },
            pressing: { plan: 5000, dispatched: 3800, completed: 2800 },
            sintering: { plan: 5000, dispatched: 3200, completed: 2500 }
          }
        },
        {
          id: 2,
          orderNumber: 'ORD-2023-002',
          productCode: 'PC-1002',
          roughSize: '150×100×50mm',
          firstBatchDate: '2023-06-15',
          planQuantity: 3000,
          productWeight: 2.5,
          totalWeight: 7500,
          machineType: 'CNC-7X',
          processes: {
            smelting: { plan: 3000, dispatched: 2900, completed: 2800 },
            hydrogen: { plan: 3000, dispatched: 2800, completed: 2600 },
            jetMill: { plan: 3000, dispatched: 2600, completed: 2300 },
            pressing: { plan: 3000, dispatched: 2500, completed: 2100 },
            sintering: { plan: 3000, dispatched: 2200, completed: 1800 }
          }
        },
        {
          id: 3,
          orderNumber: 'ORD-2023-003',
          productCode: 'PC-1003',
          roughSize: '100×60×30mm',
          firstBatchDate: '2023-06-20',
          planQuantity: 8000,
          productWeight: 0.8,
          totalWeight: 6400,
          machineType: 'CNC-3X',
          processes: {
            smelting: { plan: 8000, dispatched: 7500, completed: 7000 },
            hydrogen: { plan: 8000, dispatched: 7000, completed: 6200 },
            jetMill: { plan: 8000, dispatched: 6500, completed: 5800 },
            pressing: { plan: 8000, dispatched: 6000, completed: 5200 },
            sintering: { plan: 8000, dispatched: 5500, completed: 4800 }
          }
        },
        {
          id: 4,
          orderNumber: 'ORD-2023-004',
          productCode: 'PC-1004',
          roughSize: '200×150×60mm',
          firstBatchDate: '2023-06-25',
          planQuantity: 2000,
          productWeight: 4.2,
          totalWeight: 8400,
          machineType: 'CNC-10X',
          processes: {
            smelting: { plan: 2000, dispatched: 1800, completed: 1600 },
            hydrogen: { plan: 2000, dispatched: 1600, completed: 1400 },
            jetMill: { plan: 2000, dispatched: 1500, completed: 1200 },
            pressing: { plan: 2000, dispatched: 1400, completed: 1000 },
            sintering: { plan: 2000, dispatched: 1200, completed: 800 }
          }
        }
      ],
      processes: [
        { name: '冶炼', key: 'smelting' },
        { name: '氢破', key: 'hydrogen' },
        { name: '气流磨', key: 'jetMill' },
        { name: '压型', key: 'pressing' },
        { name: '烧结', key: 'sintering' }
      ]
    };
  },
  computed: {
    filteredOrders() {
      const query = this.searchQuery.toLowerCase();
      if (!query) return this.orders;
      
      return this.orders.filter(order => 
        order.orderNumber.toLowerCase().includes(query) || 
        order.productCode.toLowerCase().includes(query)
      );
    }
  },
  methods: {
    getProcessDelayStatus(order) {
      const delayedProcesses = [];
      const processMap = {
        smelting: '冶炼',
        hydrogen: '氢破',  // 需要排除的工序
        jetMill: '气流磨',
        pressing: '压型',
        sintering: '烧结'
      };
      
      // console.log("KKKKKKKKKKKKKKKKKKKKKKKKKKK",order)
      Object.entries(order.processes).forEach(([key, data]) => {
        if (key === 'hydrogen') return; // 排除氢破工序
        // console.log("EEEEEEEEEEEEEEEEEEEEEE",data)
        const processName = processMap[key] || key;
        // console.log("RRRRRRRRRRRRRRRRRRRRRR",processName)
        if (data.dispatched < data.plan) {
          delayedProcesses.push(`${processName}(${Math.round((data.dispatched/data.plan)*100)}%)`);
        }
      });
      // console.log("GGGGGGGGGGGGGGGGGGGG",delayedProcesses)

      return delayedProcesses.length > 0 
        ? delayedProcesses.join('、') 
        : '无延误';
    },

      // 判断订单状态文字
    orderStatusText(order) {
      const currentDate = new Date();
      const firstBatchDate = new Date(order.firstBatchDate);
      
      if (currentDate > firstBatchDate) {
        return '延误';
      } else if (currentDate.toDateString() === firstBatchDate.toDateString()) {
        return '进行中';
      } else {
        return '正常';
      }
    },
    // 动态绑定状态颜色
    orderStatusClass(order) {
      const currentDate = new Date();
      const firstBatchDate = new Date(order.firstBatchDate);
      
      return {
        'delayed': currentDate > firstBatchDate,
        'ongoing': currentDate.toDateString() === firstBatchDate.toDateString(),
        'normal': currentDate < firstBatchDate
      };
    },
    selectOrder(order) {
      this.selectedOrder = order;      
      // 更新工序进度数据
      this.processes = this.processes.map(process => {
        // console.log("CCCCCCCCCCCCCCCCCCCCCC",order.processes)
        console.log(process.key)
        const data = order.processes[process.key] || {};
        console.log(data)
        // 解构时设置默认值
        const { plan = 0, dispatched = 0, completed = 0 } = data;
        return {
          ...process,
          plan,
          dispatched,
          completed,
          ratio: plan > 0 ? Math.round((dispatched / plan) * 100) : 0, // 防止除零
          planWidth: 100,
          dispatchedWidth: (dispatched / (plan || 1)) * 100, // 二次防除零
          completedWidth: (completed / (plan || 1)) * 100
        }; 
      });
    },
    parseDate(str) {
      const [year, month, day] = str.split('-').map(Number);
      return new Date(year, month - 1, day); // 月份从 0 开始
    },
    formatCurrentTime() {
      // console.log("时间函数！！！")
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    computed_data_count(startDate_){
      const startDate = this.parseDate(startDate_);
      // console.log("startDate",startDate)
      const today_ = this.parseDate(this.formatCurrentTime());
      // console.log("today_",today_)
      const days = Math.floor((today_ - startDate) / (1000 * 60 * 60 * 24)) + 1;
      // console.log(days); // 输出 9
      return days
    },
    search_db_updatatime(){
      // 数据库查询
      console.log(this.formatCurrentTime())
      var date_from_plan = []
      var gongxu_name = ["yl","qp","qlm","yx","sj"]
      this.http.get('api/material_plan_xie/get_data_db_compute',
                          {}).then((reslut) => {
                            date_from_plan = reslut
                            // console.log("222222222222222222222",reslut)
                            for(let i=0;i<reslut.length;i++){
                              var all_gx_plan_qty = []
                              for(let j=0;j<gongxu_name.length;j++){
                                var star_string = gongxu_name[j]+"_startdate"
                                if(reslut[i][star_string] == ""){
                                  all_gx_plan_qty.push(0)
                                  // console.log("订单号······",reslut[i]["schedule_id"],i+1)
                                }else{
                                  const today = new Date(); // 获取当天日期
                                  const targetDate = new Date(reslut[i][star_string]); // 目标日期
                                  if (today < targetDate) {
                                      // console.log("当天日期比2025-6-30小");
                                      all_gx_plan_qty.push(0)
                                  } else {
                                      // console.log("当天日期不小于2025-6-30");
                                      // console.log(," ",reslut[i]["schedule_id"],i+1,reslut[i][star_string].split(" ")[0])
                                      var days_ = this.computed_data_count(reslut[i][star_string].split(" ")[0])
                                      // console.log("计算后的时间：1111     ",reslut[i]["schedule_id"],i+1,gongxu_name[j],days_,reslut[i][star_string].split(" ")[0],today," ",targetDate," ",today < targetDate)
                                      // console.log("订单号······",reslut[i]["schedule_id"],i+1)
                                      if(days_ < reslut[i][gongxu_name[j]+"_dunring"]){
                                        all_gx_plan_qty.push(days_ * reslut[i][gongxu_name[j]+"_per_in"])
                                      }else{ //total_weight
                                        all_gx_plan_qty.push(reslut[i]["total_weight"])
                                      }
                                  }
                                  
                                }
                              }
                              // console.log("LLLLLLLLLLLLLL",all_gx_plan_qty)
                              this.orders.push(
                                  {
                                    id:i+1,
                                    orderNumber: reslut[i]["schedule_id"],
                                    productCode: reslut[i]["top_id"],
                                    roughSize: reslut[i]["schedule_blank_spec"],
                                    date_first_batch: reslut[i]["date_first_batch"].split(" ")[0],
                                    planQuantity: reslut[i]["product_qty"],
                                    productWeight: reslut[i]["per_weight"],
                                    firstBatchDate: reslut[i]["date_first_batch"].split(" ")[0],
                                    totalWeight: reslut[i]["total_weight"],
                                    machineType: reslut[i]["device_type"],
                                    processes: {
                                      smelting: { plan: all_gx_plan_qty[0], dispatched: reslut[i]["Qty_yl"], completed: reslut[i]["InputQty_yl"] },
                                      hydrogen: { plan: all_gx_plan_qty[1], dispatched: reslut[i]["Qty_qp"], completed: reslut[i]["InputQty_qp"] },
                                      jetMill: { plan: all_gx_plan_qty[2], dispatched: reslut[i]["Qty_qlm"], completed: reslut[i]["InputQty_qlm"] },
                                      pressing: { plan: all_gx_plan_qty[3], dispatched: reslut[i]["Qty_yx"], completed: reslut[i]["InputQty_yx"]  },
                                      sintering: { plan: all_gx_plan_qty[4], dispatched: reslut[i]["Qty_sj"], completed: reslut[i]["InputQty_sj"]  }
                                    }
                                  },
                                )                              
                            }
                        }).catch((error) => {
                            console.log("失败",error)
                            // return "未更新"
                        });
      
    },
  },
  mounted() {
    this.orders = []
    this.search_db_updatatime()
    // 默认选择第一个订单
    if (this.orders.length > 0) {
      this.selectOrder(this.orders[0]);
    }

  }
};
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
/* 新增样式 */
.order-stats {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: 20px;
  padding: 8px 15px;
  background: #f8f9fa;
  border-radius: 20px;
  transition: all 0.3s ease;
}
/* 悬停效果 */
.order-stats:hover {
  background: #e9ecef;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.delay-tag {
  margin-left: 10px;
  padding: 2px 5px;
  border-radius: 3px;
  background-color: #ffc107;
  color: #333;
  font-size: 0.8em;
  white-space: nowrap;
}
/* 悬停显示详细信息 */
.delay-tag:hover {
  background-color: #e0a800;
  cursor: pointer;
  transform: scale(1.05);
}

/* 延误工序名称颜色 */
.delay-tag span {
  color: #ef6c00;
  font-weight: 500;
}
/* 新增状态颜色样式 */
.delayed {
  background-color: #ffe0b2 !important; /* 浅橙色背景 */
  color: #ef6c00 !important; /* 深橙色文字 */
}

.ongoing {
  background-color: #e3f2fd !important; /* 浅蓝色背景 */
  color: #1976d2 !important; /* 深蓝色文字 */
}
.normal {
  background-color: #e8f5e9 !important; /* 浅绿色背景 */
  color: #2e7d32 !important; /* 深绿色文字 */
}
.selected.delayed {
  border-left: 4px solid #ef6c00 !important;
}
.selected.ongoing {
  border-left: 4px solid #1976d2 !important;
}

.selected.normal {
  border-left: 4px solid #2e7d32 !important;
}

/* 新增冻结样式 */
.fixed-scroll {
  position: sticky;
  top: 80px; /* 根据顶部导航栏高度调整 */
  z-index: 100; /* 确保层级最高 */
  background: white; /* 背景色保持一致 */
  box-shadow: 0 4px 6px rgba(0,0,0,0.1); /* 添加阴影增强层次 */
}

body {
  background: transparent;
  padding: 20px;
  min-height: 100vh;
}

.container {
  max-width: flex;
  margin: 2rem auto 0; /* 顶部间距 */
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  padding: 20px; /* 内边距 */
  width: calc(100% - 40px); /* 两侧间距 */
}

.header {
  background: linear-gradient(to right, #2c3e50, #4a6491);
  color: white;
  padding: 20px;
  text-align: center;
  border-radius: 15px 15px 0 0;
}

.header h1 {
  font-size: 2.2rem;
  margin-bottom: 5px;
}

.header p {
  opacity: 0.8;
}

.controls {
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box input {
  width: 100%;
  padding: 10px 15px 10px 40px;
  border: 1px solid #ced4da;
  border-radius: 30px;
  font-size: 14px;
}

.search-box i {
  position: absolute;
  left: 15px;
  top: 12px;
  color: #6c757d;
}

.legend {
  display: flex;
  gap: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
}

.content {
  display: flex;
  gap: 2rem;
  padding: 20px;
  background: white;
  border-radius: 0 0 15px 15px;
  overflow: hidden; /* 防止内容溢出 */
  height: calc(100vh - 160px); /* 视口高度减去顶部固定元素 */
}

.order-list {
  width: 60% !important; /* 固定左侧宽度 */
  min-width: 600px; /* 最小宽度限制 */
  flex-shrink: 0; /* 防止收缩 */
  border-right: 1px solid #dee2e6;
  overflow-y: auto;
  padding-right: 20px;
}

.plan-comparison {
  width: 40% !important;
  padding: 20px;
  background-color: #f8fafc;
  border-radius: 15px;
}

.order-table {
  width: 100%;
  border-collapse: collapse;
}

.order-table th {
  background-color: #e9ecef;
  padding: 12px 15px;
  text-align: center;
  font-weight: 600;
  color: #495057;
  position: sticky;
  top: 0;
}

/* 表格头部固定优化 */
.order-table thead th {
  position: sticky;
  top: 0;
  background: #fff;
  z-index: 2;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  background-color: #2c3e50 !important; /* 深色背景 */
  color: white !important; /* 白色文字 */
  font-weight: 600;
  padding: 15px;
  border-bottom: 2px solid #34495e;
}

.order-table tr {
  border-bottom: 1px solid #dee2e6;
  transition: background-color 0.2s;
  text-align: center;
}

.order-table tr:hover {
  background-color: #f1f3f5;
}

.order-table td {
  padding: 12px 15px;
  color: #495057;
}

.order-table tr.selected {
  background-color: #e3f2fd;
}

.process-bars {
  padding: 5px 0;
}

.process-title {
  font-weight: bold;
  color: #2c3e50;
  /* margin-bottom: 5px; */
  display: flex;
  justify-content: space-between;
  font-size: 20px;
}

.process-bar-container {
  height: 50px;
  background-color: #e9ecef;
  border-radius: 12px;
  /* margin-bottom: 5px; */
  position: relative;
  overflow: hidden;
  box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
}

.plan-bar {
  position: absolute;
  height: 100%;
  background-color: #ff6b6b;
  border-radius: 12px 0 0 12px;
  z-index: 1;
}

.dispatched-bar {
  position: absolute;
  height: 100%;
  background-color: #51cf66;
  border-radius: 12px 0 0 12px;
  z-index: 2;
}

.completed-bar {
  position: absolute;
  height: 100%;
  background-color: #339af0;
  border-radius: 12px 0 0 12px;
  z-index: 3;
}

.process-value {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 30px;
  color: white;
  z-index: 4;
  text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}

.no-selection {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #adb5bd;
  font-size: 18px;
  text-align: center;
  padding: 20px;
}

.footer {
  padding: 20px;
  text-align: center;
  background-color: #f8f9fa;
  color: #6c757d;
  border-top: 1px solid #dee2e6;
  margin-top: 2rem;
}

.stat-box {
  background: white;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
}

.stat-title {
  font-size: 22px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #495057;
}

.stat-content {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 22px;
  font-weight: bold;
  color: #2c3e50;
}

.stat-label {
  font-size: 20px;
  color: #6c757d;
}

@media (max-width: 1200px) {
  .content {
    flex-direction: column;
    height: auto; /* 取消固定高度 */
  }
  
  .fixed-scroll {
    position: relative; /* 移动端取消固定 */
    top: auto;
  }
  
  .order-list, .plan-comparison {
    width: 100%;
  }
  
  .order-list {
    max-height: 400px;
  }
}
</style>